import json
import requests
import time
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def post_html_text(url, data):
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    try:
        r = requests.post(url, timeout=30, data=data, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)


dic = {"cursor": "{\"ct_lt\":0,\"limit\":10}",
       "h_av": "2.7.0",
       "h_did": "",
       "h_dt": "2",
       "h_m": "5bce864f47f8c223593dc722",
       "h_os": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
       "h_ts": "1540261811424",
       "mode": "cors",
       "session": "2d426ae9-68a3-4258-ac07-5f7e60e731ef"}  # json文件显示条数
data = json.dumps(dic)
url = 'https://api.zdpvt.com/api/post/flash_query'


def get_dates_kx(url, data):
    text = post_html_text(url, data)
    if not text:
        return None
    text = json.loads(text)
    data = text['data']['list']
    cursor = text['data']['cursor']
    dates = [time.strftime("%Y-%m-%d", time.localtime(date['ct'])) for date in data]
    return (dates, cursor)


def count_process_kx():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    ccs = json.dumps({"ct_lt": 0, "limit": 10})
    while a < 100:
        dic = {"cursor": ccs,
               "h_av": "2.7.0",
               "h_did": "",
               "h_dt": "2",
               "h_m": "5bce864f47f8c223593dc722",
               "h_os": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
               "h_ts": "1540261811424",
               "mode": "cors",
               "session": "2d426ae9-68a3-4258-ac07-5f7e60e731ef"}  # json文件显示条数
        data = json.dumps(dic)
        url = 'https://api.zdpvt.com/api/post/flash_query'
        print('----支点财经快讯获取第{}页----'.format(a))
        a += 1
        data = get_dates_kx(url, data)
        dates = data[0]
        ccs = data[1]
        if not dates:
            continue
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '支点'
    t1 = count_process_kx()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
